import Vue from 'vue'
import router from '@/router'
import store from '@/store'

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  let res = []
  let temp = {}
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}


/**
 * 将驼峰风格的列名转为下划线风格
 * @param string
 * @returns {*}
 */
export function toUnderScore (string) {
  return string.replace(/([A-Z])/g, function (all, letter) {
    return '_' + letter.toLowerCase();
  });
}

/**
 * 把排序方式改为缩写形式
 * @param string
 * @returns {*}
 */
export function abbreviate (order) {
  switch (order) {
    case 'ascending':
      return 'ASC';
    case 'descending':
      return 'DESC';
    default:
      return null;
  }
}

/**
 * 初始今天、本周、本月时间
 * @param date 时间标识
 * @returns {Date[]}
 */
export function getSelectDate (date) {
  let oneDayLong = 24 * 60 * 60 * 1000;
  let now = new Date();
  let startDay, endDay, morning, night, today,
    mondayTime, sundayTime, monday, sunday, weekRange,
    year, monthStartDate, nextMonthStartDate, days, monthEndDate, monthRange
  switch (date) {
    case 'theDay':
      startDay = new Date(now.getTime()).setHours(0, 0, 0, 0)
      endDay = new Date(now.getTime()).setHours(0, 0, 0, 0)
      morning = new Date(startDay)
      night = new Date(endDay)
      today = [morning, night]
      return today
    case 'theWeek':
      mondayTime = now.getTime() - (now.getDay() - 1) * oneDayLong;
      sundayTime = now.getTime() + (7 - now.getDay()) * oneDayLong;
      monday = new Date(mondayTime).setHours(0, 0, 0, 0);
      sunday = new Date(sundayTime).setHours(0, 0, 0, 0);
      weekRange = [monday, sunday];
      return weekRange;
    case 'theMonth':
      year = now.getFullYear();
      monthStartDate = new Date(year, now.getMonth(), 1);// 当前月1号
      nextMonthStartDate = new Date(year, now.getMonth() + 1, 0);// 下个月1号
      days = (nextMonthStartDate.getTime() + oneDayLong - monthStartDate.getTime()) / oneDayLong;// 计算当前月份的天数
      monthEndDate = new Date(year, now.getMonth(), days).setHours(0, 0, 0, 0);
      monthRange = [monthStartDate, monthEndDate];
      return monthRange;
    default:
      break
  }
}

/**
 * 自定义校验
 */
Vue.prototype.$validateFields = function (type, num) {
  switch (type) {
    case 'NumberChar':
      return function (rule, value, callback) {
        let patrn = /^[A-Za-z0-9-\\_]+$/
        if (value && !patrn.exec(value)) {
          callback(new Error('只能输入字母、数字、下划线、横线'))
        }
        callback()
      }
    case 'Number':
      return function (rule, value, callback) {
        if (value && (isNaN(value) || value <= 0)) {
          callback(new Error('请输入大于0的数字'))
        }
        callback()
      }
    case 'NumberToFixed':
      return function (rule, value, callback) {
        let str = value.split('.').length > 1 && value.split('.')[1]
        if (value && (isNaN(value) || str.length > num || value <= 0)) {
          callback(new Error('请输入大于0的数字且最多保留' + num + '小数'))
        }
        callback()
      }
  }
}

Vue.prototype.$formatDate = function (date, formatType, endType) {
  if (date) {
    if (date.length === 6) {
      const tempYear = date.substring(0, 4)
      const tempMon = date.substring(4)
      date = `${tempYear}-${tempMon}`
    }
    let year = new Date(date).getFullYear()
    let month = new Date(date).getMonth() + 1
    month = parseInt(month) < 10 ? `0${month}` : month
    let day = new Date(date).getDate()
    let hour = new Date(date).getHours()
    let min = new Date(date).getMinutes()
    let sec = new Date(date).getSeconds()
    day = parseInt(day) < 10 ? `0${day}` : day
    if (endType === 'Month') {
      return year + (formatType || '年') + month + (formatType || '月')
    } else if (endType === 'Second') {
      return year + (formatType || '年') + month + (formatType || '月') + day + (formatType || '日') + ' ' + hour + (formatType ? ':' : '时') + min + (formatType ? ':' : '分') + sec + (formatType ? ':' : '秒')
    } else {
      return year + (formatType || '年') + month + (formatType || '月') + day + (formatType || '日')
    }
  } else {
    return ''
  }
}

// 清空表单中的值
Vue.prototype.$resetData = function (data) {
  for (let key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      if (Array.isArray(key)) {
        data[key] = []
      } else {
        data[key] = ''
      }
    }
  }
}

/**
 * 自定义校验
 */
Vue.prototype.$validateFields = function (type, num) {
  switch (type) {
    case 'NumberChar':
      return function (rule, value, callback) {
        let patrn = /^[A-Za-z0-9-\\_]+$/
        if (value && !patrn.exec(value)) {
          callback(new Error('只能输入字母、数字、下划线、横线'))
        }
        callback()
      }
    case 'Number':
      return function (rule, value, callback) {
        if (value && (isNaN(value) || value <= 0)) {
          callback(new Error('请输入大于0的数字'))
        }
        callback()
      }
    case 'NumberToFixed':
      return function (rule, value, callback) {
        let str = value.split('.').length > 1 && value.split('.')[1]
        if (value && (isNaN(value) || str.length > num || value <= 0)) {
          callback(new Error('请输入大于0的数字且最多保留' + num + '小数'))
        }
        callback()
      }
    case 'phone':
      return function (rule, value, callback) {
        let patrn = /^1[3,5,8]\d{9}$/;
        if (value && !patrn.exec(value)) {
          callback(new Error('请输入正确的手机格式'))
        }
        callback()
      }
    case 'email':
      return function (rule, value, callback) {
        let patrn = /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
        if (value && !patrn.exec(value)) {
          callback(new Error('请输入正确的邮箱格式'))
        }
        callback()
      }
    case 'idCard':
      return function (rule, value, callback) {
        let patrn = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        if (value && !patrn.exec(value)) {
          callback(new Error('请输入正确身份证号'))
        }
        callback()
      }
  }
}

// 格式化时间
Vue.prototype.$formatDate = function (date, formatType = '', endType) {
  if (date) {
    if (date.length === 6) {
      const tempYear = date.substring(0, 4)
      const tempMon = date.substring(4)
      date = `${tempYear}-${tempMon}`
    }
    let year = new Date(date).getFullYear()
    let month = new Date(date).getMonth() + 1
    month = parseInt(month) < 10 ? `0${month}` : month
    let day = new Date(date).getDate()
    let hour = new Date(date).getHours()
    let min = new Date(date).getMinutes()
    let sec = new Date(date).getSeconds()
    day = parseInt(day) < 10 ? `0${day}` : day
    hour = parseInt(hour) < 10 ? `0${hour}` : hour
    min = parseInt(min) < 10 ? `0${min}` : min
    sec = parseInt(sec) < 10 ? `0${sec}` : sec
    if (endType === 'Month') {
      return year + (formatType == null ? '年' : formatType) + month + (formatType == null ? '月' : '')
    } else if (endType === 'Second') {
      return year + (formatType == null ? '年' : formatType) + month + (formatType == null ? '月' : formatType) + day + (formatType == null ? '日' : '') + ' ' + hour + (formatType == null ? '时' : ':') + min + (formatType == null ? '分' : ':') + sec + (formatType == null ? '秒' : '')
    } else {
      return year + (formatType == null ? '年' : formatType) + month + (formatType == null ? '月' : formatType) + day + (formatType == null ? '日' : '')
    }
  } else {
    return ''
  }
}
